package com.ruoyi.studentHelp.AceUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class LongEncryptionDemo {

    private static final String ALGORITHM = "AES";
    private static final byte[] KEY_BYTES = "woniucsdnvip8888".getBytes(); // 16字节密钥

    public static String encryptLong(Long id) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY_BYTES, ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 将Long转换成字节数组
        byte[] idBytes = longToByteArray(id);
        // 执行加密
        byte[] encryptedBytes = cipher.doFinal(idBytes);
        // 将加密后的字节数组转换为Base64字符串以便于传输或存储
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static Long decryptLong(String encryptedText) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY_BYTES, ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        // 将Base64字符串解码回字节数组
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        // 执行解密
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        // 将解密后的字节数组转换回Long
        return byteArrayToLong(decryptedBytes);
    }

    private static byte[] longToByteArray(long value) {
        byte[] bytes = new byte[8];
        for (int i = 0; i < 8; i++) {
            bytes[i] = (byte) (value >>> (8 * (7 - i)));
        }
        return bytes;
    }

    private static long byteArrayToLong(byte[] bytes) {
        long result = 0;
        for (int i = 0; i < 8; i++) {
            result = (result << 8) | (bytes[i] & 0xFF);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        Long id = 1314520L;
        String encryptedId = encryptLong(id);
        System.out.println("加密后的Long值：" + encryptedId);
        Long decryptedId = decryptLong(encryptedId);
        System.out.println("解密后的Long值：" + decryptedId);
    }
}